<template>
  <div class="my-rescues">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1>宠物救助信息</h1>
      </div>

      <!-- 筛选和搜索 -->
      <div class="filters">
        <div class="filter-group">
          <label>状态筛选：</label>
          <el-select v-model="filterStatus">
            <el-option value="" label="全部状态"></el-option>
            <el-option label="待救助" :value="1" />
            <el-option label="救助中" :value="2" />
            <el-option label="已救助" :value="3" />
            <el-option label="已关闭" :value="4" />
          </el-select>
        </div>

        <div class="filter-group">
          <label>紧急程度：</label>
          <el-select v-model="filterUrgency">
            <el-option value="" label="全部"></el-option>
            <el-option value="非常紧急" label="非常紧急"></el-option>
            <el-option value="紧急" label="紧急"></el-option>
            <el-option value="一般" label="一般"></el-option>

          </el-select>
        </div>

        <div class="search-group">
          <el-input type="text" v-model="searchKeyword" @input="handleSearchInput" placeholder="输入救助标题"
            class="search-input" />
        </div>
        <div class="filter-group">
          <el-button type="primary" @click="applyFilters">筛选</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </div>
      </div>
      <!-- 加载状态 -->
      <el-card v-if="loading" class="loading-card">
        <div class="loading-content">
          <i class="el-icon-loading"></i>
          <span>加载中...</span>
        </div>
      </el-card>

      <!-- 空状态 -->
      <div v-else-if="rescues.length === 0" class="empty-state">
        <div class="empty-icon">📋</div>
        <h3>还没有发布救助信息</h3>
        <p>发现流浪宠物？立即发布救助信息帮助它们</p>
      </div>

      <!-- 救助信息列表 -->
      <div v-else class="rescue-list">
        <div v-for="rescue in rescues" :key="rescue.id" class="rescue-card" @click="goToDetail(rescue.id)">
          <!-- 卡片头部 -->
          <div class="card-header">
            <div class="rescue-info">
              <h3 class="rescue-title">{{ rescue.title }}</h3>
              <div class="rescue-meta">
                <span class="species">{{ rescue.species }}</span>
                <span class="location">📍 {{ rescue.location }}</span>
                <span class="date">🕒 {{ formatDate(rescue.foundDate) }}</span>
              </div>
            </div>
            <div class="rescue-status">
              <span class="status-badge" :class="setStatusText(rescue.status)">
                {{ getStatusText(rescue.status) }}
              </span>
              <span class="urgency-badge" :class="setUrgencyText(rescue.urgency)">
                {{ rescue.urgency }}
              </span>
            </div>
          </div>

          <!-- 卡片内容 -->
          <div class="card-content">
            <div class="rescue-photos" v-if="rescue.photos && rescue.photos.length > 0">
              <img :src="rescue.photos[0]" :alt="rescue.title" class="main-photo" />
              <div v-if="rescue.photos.length > 1" class="photo-count">
                +{{ rescue.photos.length - 1 }}
              </div>
            </div>

            <div class="rescue-details">
              <p class="description">{{ rescue.description }}</p>
              <div class="health-info">
                <span class="health-status" :class="setHealthStatusText(rescue.healthStatus)">
                  {{ rescue.healthStatus }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-wrapper">
        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAllRescues } from '../api/rescue-info'

export default {
  name: 'MyRescues',
  data() {
    return {
      loading: true,
      rescues: [],
      filterStatus: '',
      filterUrgency: '',
      searchKeyword: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      showDeleteModal: false,
      deleteTarget: null,
      searchTimer: null // 搜索防抖定时器
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn']),
  },
  created() {
    this.fetchRescues()
  },
  beforeDestroy() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
    }
  },
  methods: {
    // 跳转详情页
    goToDetail(id) {
      this.$router.push(`/rescue-detail/${id}`)
    },
    async fetchRescues() {
      try {
        this.loading = true

        // 调用getAllRescues接口
        const response = await getAllRescues({
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: this.filterStatus,
          urgency: this.filterUrgency,
          title: this.searchKeyword
        })

        if (response.code === 200) {
          this.rescues = response.data.rows
          this.total = response.data.total || 0
        } else {
          this.rescues = []
          this.total = 0
        }
      } catch (error) {
        this.rescues = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 搜索输入防抖处理
    handleSearchInput() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        this.applyFilters()
      }, 500)
    },

    // 重置
    resetFilter() {
      this.filterStatus = ''
      this.filterUrgency = ''
      this.searchKeyword = ''
      this.currentPage = 1
      this.fetchRescues()
    },

    // 应用筛选条件
    applyFilters() {
      this.currentPage = 1
      this.fetchRescues()
    },

    // 分页改变
    handlePageChange(page) {
      this.currentPage = page
      this.fetchRescues()
    },

    // 每页条数改变
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchRescues()
    },

    editRescue(rescue) {
      // 跳转到编辑页面
      this.$router.push(`/rescue-submit?edit=${rescue.id}`)
    },

    deleteRescue(rescue) {
      this.deleteTarget = rescue
      this.showDeleteModal = true
    },

    cancelDelete() {
      this.showDeleteModal = false
      this.deleteTarget = null
    },

    async confirmDelete() {
      try {
        // TODO: 调用删除API
        // await deleteRescue(this.deleteTarget.id)

        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        // 删除成功后重新获取数据
        this.$message.success('删除成功')
        this.fetchRescues()

      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败，请重试')
      } finally {
        this.cancelDelete()
      }
    },
    setStatusText(status) {
      const statusMap = {
        1: 'pending',
        2: 'in_progress',
        3: 'resolved',
        4: 'closed'
      }
      return statusMap[status] || status
    },

    setUrgencyText(status) {
      const statusMap = {
        '一般': 'low',
        '紧急': 'medium',
        '非常紧急': 'high',
      }
      return statusMap[status] || status
    },

    setHealthStatusText(status) {
      const statusMap = {
        '良好': 'good',
        '受伤': 'injured',
        '生病': 'sick',
        '危重': 'critical'
      }
      return statusMap[status] || status
    },

    getStatusText(status) {
      const statusMap = {
        1: '待救助',
        2: '救助中',
        3: '已救助',
        4: '已关闭'
      }
      return statusMap[status] || status
    },

    formatDate(dateString) {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) {
        return '今天'
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString()
      }
    }
  }
}
</script>

<style scoped>
.my-rescues {
  background: #f8f9fa;
  min-height: 100vh;
  padding: 20px 0;
}


.filters {
  display: flex;
  gap: 20px;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-weight: 500;
  color: #333;
  white-space: nowrap;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
}

.search-group {
  flex: 1;
  min-width: 200px;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #666;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
}

.empty-state h3 {
  color: #333;
  margin: 0 0 12px 0;
}

.empty-state p {
  color: #666;
  margin: 0 0 24px 0;
}

.btn-primary {
  background: #007bff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: bold;
}

.rescue-list {
  display: grid;
  gap: 20px;
}

.rescue-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.rescue-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px 20px 0 20px;
}

.rescue-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.rescue-meta {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #666;
  flex-wrap: wrap;
}

.rescue-status {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-end;
}

.status-badge,
.urgency-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
  white-space: nowrap;
}

.status-badge.pending {
  background: #fff3cd;
  color: #856404;
}

.status-badge.in_progress {
  background: #d1ecf1;
  color: #0c5460;
}

.status-badge.resolved {
  background: #d4edda;
  color: #155724;
}

.status-badge.closed {
  background: #f8d7da;
  color: #721c24;
}

.urgency-badge.low {
  background: #e2e3e5;
  color: #383d41;
}

.urgency-badge.medium {
  background: #fff3cd;
  color: #856404;
}

.urgency-badge.high {
  background: #f8d7da;
  color: #721c24;
}

.card-content {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.rescue-photos {
  position: relative;
  flex-shrink: 0;
}

.main-photo {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
}

.photo-count {
  position: absolute;
  bottom: 4px;
  right: 4px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.rescue-details {
  flex: 1;
}

.description {
  color: #666;
  line-height: 1.5;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.health-status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.health-status.good {
  background: #d4edda;
  color: #155724;
}

.health-status.injured {
  background: #fff3cd;
  color: #856404;
}

.health-status.sick {
  background: #f8d7da;
  color: #721c24;
}

.health-status.critical {
  background: #f5c6cb;
  color: #721c24;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px 20px 20px;
  border-top: 1px solid #f0f0f0;
  margin-top: 16px;
  padding-top: 16px;
}

.rescue-stats {
  display: flex;
  gap: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #666;
}

.stat-icon {
  font-size: 16px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.btn-action {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: #f8f9fa;
  cursor: pointer;
  transition: background 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-action:hover {
  background: #e9ecef;
}

.btn-action.danger:hover {
  background: #f8d7da;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding: 20px 0;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 24px;
  border-radius: 12px;
  max-width: 400px;
  width: 90%;
}

.modal h3 {
  margin: 0 0 16px 0;
  color: #333;
}

.modal p {
  margin: 0 0 8px 0;
  color: #666;
}

.warning {
  color: #dc3545;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.btn-cancel,
.btn-danger {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
}

.btn-cancel {
  background: #f8f9fa;
  color: #666;
}

.btn-danger {
  background: #dc3545;
  color: white;
}
</style>